package com.imooc.spring.jdbc.service;

import com.imooc.spring.jdbc.dao.EmployeeDao;
import com.imooc.spring.jdbc.entity.Employee;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Date;

public class EmployeeService {
    private EmployeeDao employeeDao;
//    private DataSourceTransactionManager transactionManager;
    private BatchService batchService;

    public EmployeeDao getEmployeeDao() {
        return employeeDao;
    }

    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    public BatchService getBatchService() {
        return batchService;
    }

    public void setBatchService(BatchService batchService) {
        this.batchService = batchService;
    }
//    public DataSourceTransactionManager getTransactionManager() {
//        return transactionManager;
//    }
//
//    public void setTransactionManager(DataSourceTransactionManager transactionManager) {
//        this.transactionManager = transactionManager;
//    }

    /*public void batchImport() {
        // 定义了事务默认的标准配置
        TransactionDefinition definition = new DefaultTransactionDefinition();
        // 开始事务
        TransactionStatus status = transactionManager.getTransaction(definition);
        try{
            for (int i = 1; i < 11; i++) {
                *//*if (i == 3) {
                    throw new RuntimeException("模拟异常");
                }*//*
                Employee employee = new Employee();
                employee.setEno(8000 + i);
                employee.setEname("张三" + i);
                employee.setSalary(4000f + i);
                employee.setDname("市场部");
                employee.setHireDate(new Date());
                employeeDao.insert(employee);
            }
            // 提交事务
            transactionManager.commit(status);
        }catch(Exception e){
            transactionManager.rollback(status);
            e.printStackTrace();
        }
    }*/
    public void batchImport() {
        for (int i = 1; i < 11; i++) {
            /*if (i == 3) {
                throw new RuntimeException("模拟异常");
            }*/
            Employee employee = new Employee();
            employee.setEno(8000 + i);
            employee.setEname("张三" + i);
            employee.setSalary(4000f + i);
            employee.setDname("市场部");
            employee.setHireDate(new Date());
            employeeDao.insert(employee);
        }
    }
    public void startImportJob() {
        // 启动批量导入
        batchService.importJob1();
        if (1==1){
            throw new RuntimeException("测试异常");
        }
        batchService.importJob2();
    }
}
